type EventHandler = (...args: any[]) => any;

class EventEmitter {
  private c = new Map<string, EventHandler[]>();

  // 订阅指定的主题
  subscribe (topic:string, ...handlers:EventHandler[]) {
    let topics = this.c.get(topic)
    if (!topics) {
      this.c.set(topic, topics = [])
    }
    topics.push(...handlers)
  }

  // 取消订阅
  unsubscribe (topic:string, handler?:EventHandler) {
    if (!handler) {
      return this.c.delete(topic)
    }
    const topics = this.c.get(topic)
    if (!topics) {
      return false
    }
    const index = topics.indexOf(handler)
    if (!~index) {
      topics.splice(index, 1)
      if (topics.length) {
        this.c.delete(topic)
      }
      return true
    }
    return false
  }
}
